package com.yuwj.chinaa.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.orhanobut.logger.Logger;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.entity.EntityAppInfo;
import com.yuwj.chinaa.entity.EntityUser;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.ActivityCollectUtil;
import com.yuwj.chinaa.util.InstallApkUtil;
import com.yuwj.chinaa.util.SharedpreferenceUtil;
import com.yuwj.chinaa.util.ToastUtil;
import com.yuwj.chinaa.util.ValidatonCheckUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class LoginActivity extends BaseActivity {
    @BindView(R.id.et_user_accont)
    EditText etUserAccount;
    @BindView(R.id.et_user_password)
    EditText etPassword;
    @BindView(R.id.iv_password_eye)
    ImageView ivPasswordEye;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @BindView(R.id.tv_register)
    TextView tvRegister;

    int passwordShowType = 0;//0-隐藏，1-开启
    IPresenter presenter;

    final int REQ_CODE_WITH_REQUEST_PERMISSION = 1;//获取权限

    public static Intent createIntent(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        return intent;
    }


    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_login;
    }

    @Override
    public void initParam() {
        presenter = new PresenterImpl(this);
    }

    @Override
    public void initView() {
        String username = SharedpreferenceUtil.getInstance().getUsername(context);
        etUserAccount.setText(username);
        if(username.equals("13125085261")){
            etPassword.setText("wu111111");
        }else if(username.equals("15971439381")){
            etPassword.setText("111111");
        } if(username.equals("15102778972")){
            etPassword.setText("123456");
        } if(username.equals("13476175971")){
            etPassword.setText("123456");
        }
    }

    @Override
    public void initOperator() {
        requestPermissions();
        JSONObject paramWithAppInfo = new JSONObject();
        try {
            paramWithAppInfo.put("isIos", "2");//是否是IOS : 1：是， 否则：否
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.appInfo(paramWithAppInfo.toString());
    }

    /**
     * 授权 只有在android6.0以后才会使用到
     */
    private void requestPermissions() {
        // 版本判断。当手机系统大于 23 时[6.0]，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Logger.i("需要动态获取权限");
            PermissionGen.with(this)
                    .addRequestCode(REQ_CODE_WITH_REQUEST_PERMISSION)
                    .permissions(
                            Manifest.permission.RECORD_AUDIO,
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.CAMERA,
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.INTERNET,
                            Manifest.permission.RECORD_AUDIO,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .request();
        } else {
            Logger.i("不需要动态获取权限");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = REQ_CODE_WITH_REQUEST_PERMISSION)
    public void onPermissionsSuccess() {
        Logger.i("动态获取权限成功");
    }

    @PermissionFail(requestCode = REQ_CODE_WITH_REQUEST_PERMISSION)
    public void onPermissionsFail() {
        ToastUtil.getInstance().shortLength(context, "动态获取权限失败");
    }


    @OnClick({ R.id.iv_password_eye, R.id.btn_login, R.id.tv_forget_password, R.id.tv_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_password_eye:
                switch (passwordShowType) {
                    case 0://开启
                        ivPasswordEye.setImageResource(R.mipmap.ic_password_eye_visible);
                        etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);//设置密码可见
                        etPassword.setSelection(etPassword.getText().toString().length());
                        etPassword.requestFocus();
                        passwordShowType = 1;
                        break;
                    case 1://隐藏
                        ivPasswordEye.setImageResource(R.mipmap.ic_password_eye_visible);
                        etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);//设置密码不可见，如果只设置TYPE_TEXT_VARIATION_PASSWORD则无效
                        etPassword.setSelection(etPassword.getText().toString().length());
                        etPassword.requestFocus();
                        passwordShowType = 0;
                        break;

                }

                break;
            case R.id.btn_login:
                String username = etUserAccount.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                    ToastUtil.getInstance().shortLength(context, "请输入用户名和密码");
                    return;
                }
                SharedpreferenceUtil.getInstance().saveUsername(context, username);
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("uphone", username);
                    jsonObject.put("upwd", password);
                    if (ValidatonCheckUtil.isMobile(username)) {
                        jsonObject.put("type", 1 + "");//1是手机(新系统),0是编号(老系统)
                    } else {
                        jsonObject.put("type", 0 + "");//1是手机(新系统),0是编号(老系统)
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                presenter.userLogin(jsonObject.toString());
                break;
            case R.id.tv_forget_password:
                startActivity(ForgetPasswordActivity.createIntent(context));
                break;
            case R.id.tv_register:
                startActivity(RegisterActivity.createIntent(context));
                break;
        }
    }

    @Override
    public void onUserLoginSuccess(EntityUser entityUser) {
        super.onUserLoginSuccess(entityUser);
        //登录成功,把token放进header中
        HttpHeaders headers = new HttpHeaders();
        headers.put("access_token", entityUser.getToken());
        OkGo.getInstance().addCommonHeaders(headers);
        SharedpreferenceUtil.getInstance().saveUserInfo(context, entityUser);
        JSONObject jsonObjectWithUserInfo = new JSONObject();
        presenter.userGetUser(jsonObjectWithUserInfo.toString());
    }

    @Override
    public void onUserLoginFail(Exception e) {
        super.onUserLoginFail(e);
        ToastUtil.getInstance().shortLength(context, "" + e.getMessage());
    }


    @Override
    public void onUserGetUserSuccess(EntityUser entityUser) {
        super.onUserGetUserSuccess(entityUser);
        EntityUser userWithLocal = SharedpreferenceUtil.getInstance().getUserInfo(context);
        entityUser.setToken(userWithLocal.getToken());
        SharedpreferenceUtil.getInstance().saveUserInfo(context, entityUser);
        finish();
        startActivity(MainActivity.createIntent(context));
    }

    @Override
    public void onUserGetUserFail(Exception e) {
        super.onUserGetUserFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }

    AlertDialog alertDialogWithUpdate;

    @Override
    public void onAppInfoSuccess(final EntityAppInfo entityAppInfo) {
        super.onAppInfoSuccess(entityAppInfo);
        SharedpreferenceUtil.getInstance().saveUpdateInfo(context, entityAppInfo);
        // 获取当前软件版本
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return;
        }
        // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        int localVersionCode = packageInfo.versionCode;
        String localVersionName = packageInfo.versionName;
        // 服务端软件版本
        String serverVersionCode = entityAppInfo.getVersion();
        //此处是服务端理解错误,服务端的versionCode对应安卓apk的versionName,所以我们判断,服务端的versionCode和本地versionName不一样即进行更新.
        if (!serverVersionCode.equals(localVersionName)) {
            //弹出对话框提示版本更新.
//            new CheckUpdateUtil().showUpdateTipDialog(LoginActivity.this, entityAppInfo, 1);

            if (alertDialogWithUpdate == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        try {
                            Uri uri = Uri.parse(entityAppInfo.getDownloadurl() + "");
                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //由于跳转到浏览器之后,此对话框会消失,为了达到强制退出的效果,所以跳转完成之后退出程序
                        ActivityCollectUtil.getInstance().finishAll();
                        android.os.Process.killProcess(android.os.Process.myPid());
                        System.exit(0);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 退出程序
                        ActivityCollectUtil.getInstance().finishAll();
                        android.os.Process.killProcess(android.os.Process.myPid());
                        System.exit(0);
                    }
                }).setTitle("版本更新").setMessage(entityAppInfo.getContent() + "");

                alertDialogWithUpdate = builder.create();
                alertDialogWithUpdate.setCanceledOnTouchOutside(false);
                alertDialogWithUpdate.setCancelable(false);
            }
            alertDialogWithUpdate.show();
        }
    }


    @Override
    public void onAppInfoFail(Exception e) {
        super.onAppInfoFail(e);
    }


    @Override
    public void onDownloadFileSuccess(File file) {
        super.onDownloadFileSuccess(file);
        String fileName = file.getName();
        if (fileName.endsWith("apk")) {
            //安装
            new InstallApkUtil().installApk(context, file.getAbsolutePath());
        }
    }

    public IPresenter getPresenter() {
        return presenter;
    }

    public void setPresenter(IPresenter presenter) {
        this.presenter = presenter;
    }
}
